package aliyun

import (
	"errors"
	"fmt"
	"io"

	"github.com/segmentfault/pacman/log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/apache/incubator-answer/internal/store"
)

type OSS struct {
	Endpoint   string `json:"endpoint" mapstructure:"endpoint" yaml:"endpoint"`
	AccessKey  string `json:"access_key" mapstructure:"access_key" yaml:"access_key"`
	SecretKey  string `json:"secret_key" mapstructure:"secret_key" yaml:"secret_key"`
	BucketName string `json:"bucket_name" mapstructure:"bucket_name" yaml:"bucket_name"`
}

// Global OSS Client
// InitOSS 初始化 OSS 客户端
var (
	OSSClient *oss.Client
	OSSBucket *oss.Bucket
)

func InitOSS(cfg OSS) error {
	if cfg.Endpoint == "" || cfg.AccessKey == "" || cfg.SecretKey == "" {
		log.Errorf("aliyun oss options is invalid")
		return fmt.Errorf("aliyun oss options is invalid")
	}

	var err error
	OSSClient, err = oss.New(cfg.Endpoint, cfg.AccessKey, cfg.SecretKey)
	if err != nil {
		log.Errorf("初始化 OSS 客户端失败: %v", err)
		return fmt.Errorf("初始化 OSS 客户端失败: %v", err)
	}

	OSSBucket, err = OSSClient.Bucket(cfg.BucketName)
	if err != nil {
		log.Errorf("初始化 OSSBucket 失败: %v", err)
		return fmt.Errorf("初始化 OSSBucket 失败: %v", err)
	}

	return nil
}

func UploadPutObject(fileName string, src io.Reader) (*store.UploadRes, error) {
	// 检查 OSSBucket 是否已初始化
	if OSSBucket == nil {
		log.Errorf("OSSBucket is not initialized")
		return nil, errors.New("OSSBucket is not initialized")
	}

	// 检查 src 是否为 nil
	if src == nil {
		log.Errorf("src is nil")
		return nil, errors.New("src is nil")
	}

	// 尝试上传文件
	if err := OSSBucket.PutObject(fileName, src); err != nil {
		log.Errorf("failed to put object: %v", err)
		return nil, err
	}

	// 获取下载 URL
	downloadUrl, err := OSSBucket.SignURL(fileName, oss.HTTPGet, 36000)
	if err != nil {
		log.Errorf("failed to get download URL: %v", err)
		return nil, err
	}

	log.Infof("Download URL: %s", downloadUrl)
	return &store.UploadRes{DownloadURL: downloadUrl}, nil
}
